package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.log.InitLog;
import com.example.log.UpdateLog;
import com.example.pojo.PageBean;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vd.dto.UserDTO;
import com.example.vd.vo.LoginVo;
import com.example.vd.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.example.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author fzy'
 * @since 2024-08-08
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public Result tryLogin(LoginVo loginVo) {
        String nickname = loginVo.getNickname();
        String password = loginVo.getPassword();
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<User>()
                .eq(nickname!=null,User::getNickname,nickname)
                .eq(password!=null,User::getPassword,password)
                .eq(User::getStatus,1)
                .eq(User::getIsDeleted,0);
        User user = getOne(wrapper);
        if (BeanUtil.isEmpty(user)) {
            log.info("登录失败");
            return Result.error("用户名或密码错误,或账号被锁定");
        }
        //存入redis
        //1.生成随机token
        String token= UUID.randomUUID().toString();
        //2.拷贝user中关键信息到userDto
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        userDTO.setToken(token);
        log.info("userDto: {}",userDTO);
        //3.将userDto转Map结构便于存Redis
        Map<String, Object> userDtoMap = BeanUtil.beanToMap(userDTO,new HashMap<String,Object>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fileName,fileValue)->fileValue.toString()));
        //4.存入redis
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userDtoMap);
        redisTemplate.expire(LOGIN_USER_KEY+token,30L, TimeUnit.MINUTES);

        return Result.succeed(userDTO);
    }

    public Result getUserList(PageBean pageBean, String idCard, String nickname) {
        Long currentPage = pageBean.getCurrentPage();
        Long pageSize = pageBean.getPageSize();
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<User>()
                .eq(User::getIsDeleted,0)
                .like(idCard!=null,User::getId,idCard)
                .like(nickname!=null,User::getNickname,nickname);
        Page<User> page=new Page<User>(currentPage,pageSize);
        page(page,wrapper);
        List<User> list = page.getRecords();
        return Result.succeed(list);
    }
    public Result deletedById(Long id) {
        LambdaUpdateWrapper<User> wrapper=new LambdaUpdateWrapper<User>()
                .eq(User::getId,id)
                .set(User::getIsDeleted,1);
        boolean type = update(wrapper);
        return type ? Result.succeed() : Result.error();
    }
    @UpdateLog
    public Result updateByUser(UserVo uservo) {
        User user = BeanUtil.toBean(uservo, User.class);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>()
                .eq(User::getIsDeleted, 0)
                .eq(User::getId, user.getId());
        boolean type = update(user, updateWrapper);
        return type ? Result.succeed() : Result.error();
    }
    @InitLog
    public Result insertByUser(UserVo uservo) {
        try {
            User user = BeanUtil.toBean(uservo, User.class);
            user.setId(null);
            System.out.println("user: "+user);
            save(user);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("必要数据不完整,请检查后重试~");
        }
        return Result.succeed();
    }

    public Result changeStatus(Long id, Boolean status) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>()
                .set(User::getStatus, status)
                .set(User::getUpdateTime, LocalDateTime.now())
                .eq(User::getId, id);
        boolean type = update(updateWrapper);
        return type ? Result.succeed() : Result.error("选择数据异常,请刷新后重试");
    }
    @InitLog
    public Result registerByUser(UserVo uservo) {
        User user = BeanUtil.toBean(uservo, User.class);
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<User>()
                .eq(user.getIdCard()!=null, User::getIdCard,user.getIdCard())
                .eq(User::getIsDeleted, 0);
        User one = getOne(wrapper);
        if (BeanUtil.isEmpty(one)){
            user.setRole(2);
            save(user);
            return Result.succeed();
        }
        else
        {
            return Result.error("已注册~");
        }

    }
}
